<template>
    <div ref="line" className="container"></div>
</template>
<script>
import baseComp from "./baseComp";

export default {
    name: "newEchartsLine",
    extends: baseComp,
    model: {
        prop: 'echartsValue',
        event: 'newEchartsLineChange'
    },
    props: {
        myData: {
            type: Object,
            default: () => {
            },
        },
        requstParams: {
            type: Object,
            default: () => {
            },
        },
        echartsValue: [String]
    },
    data() {
        return {
            id: 'main',
            // name: "childStep",
            chartView: null, //图表绘画
            // 定义了样式的数据，没有具体数据的参数
            option: {
                backgroundColor: "rgba(255, 255, 255, 0)",
                title: {
                    text: "",
                    textStyle: {
                        color: "#28394f",
                        fontWeight: "normal",
                    },
                    left: "50",
                    top: "10",
                },
                tooltip: {
                    trigger: "axis",
                },
                legend: {
                    x: '3%',
                    y: '10%',
                    show: true
                },
                grid: {
                    left: '3%',
                    right: '6%',
                    bottom: '3%',
                    top: '0%',
                    containLabel: true,
                },
                xAxis: {
                    show: true,
                    name: "",
                    type: "category",
                    boundaryGap: true,
                    axisLabel: {
                        show: true,
                        color: "#616467",
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "#dcdcdc",
                        },
                    },
                    data: [],
                },
                yAxis: {
                    name: "",
                    type: "value",
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "#dcdcdc",
                        },
                    },
                    axisLabel: {
                        color: "#616467",
                        // formatter: "{value} Mbps",
                    },
                },
                series: [],
            },
            // 父组件值
            key: '',
        };
    },
    created() {
    },
    mounted() {
        // 初始化echart的图表
        // this.initChart();
        // // 请求初始化数据
        // this.$nextTick(() => {
        //   let url = this.requstParams.initUrl;
        //   let method = this.requstParams.initMethod;
        //   if (url && method) {
        //     let form = this.getRequestParam()
        //     this.init(method, url, form);
        //   }
        // });
    },


    watch: {
        echartsValue: {
            handler(val) {
                if (val) {
                    this.getRemoteData(val);
                }
            },
            deep: true,
        },
        myData: {
            handler(val) {
                if (val) {
                    this.initData();
                    this.initChart();
                }
            },
            deep: true,
            immediate: true
        },
        requstParams: {
            handler(val) {
                if (val) {
                    // 用于echart的画图的id，当相同图表同时渲染是，id可作用唯一键
                    this.id = val.id
                    if (val.newHeight || val.newWidth) {
                        this.resizeContainer();
                    }
                    this.getRemoteData();
                }
            },
            immediate: true,
            deep: true,
        },
    },
    methods: {
        /**
         * 获取初始化请求值的请求参数体
         */
        getRequestParam() {
            let requstForm = this.requstParams.initRequstForm;
            let form = {}
            if (requstForm) {
                for (let i = 0; i < requstForm.length; i++) {
                    form[requstForm[i].label] = requstForm[i].value;
                }
            }
            if (this.echartsValue !== null && this.echartsValue !== '') {
                form['form'] = {'key': this.key}
            }
            return form
        },
        /**
         * 初始化echarts对象和dom元素
         */
        initChart() {
            if (!this.chartView) {
                this.$nextTick(() => {
                    let dom = this.$refs.line;
                    this.chartView = this.$echarts.init(dom);
                    this.chartView.setOption(this.option);
                    let myChart = this.chartView;
                    window.addEventListener("resize", () => {
                        myChart.resize();
                    });
                })
            }
        },
        //模拟数据
        initData() {
            console.log("mydata", this.myData);
            this.option.grid.top = this.myData.tableTop;
            this.option.grid.bottom = this.myData.tableButton;
            this.option.grid.left = this.myData.tableLeft;
            this.option.grid.right = this.myData.tableRight;
            this.option.backgroundColor = this.myData.backgroundColor;
            this.option.title.show = this.myData.title.show;
            this.option.title.text = this.myData.title.text;
            this.option.title.left = this.myData.title.left;
            this.option.title.top = this.myData.title.top;
            this.option.title.textStyle.fontSize = this.myData.title.fontSize;
            this.option.legend.data = this.myData.legend.data;
            this.option.legend.show = this.myData.legend.show;
            this.option.legend.x = this.myData.legend.xAxis;
            this.option.legend.y = this.myData.legend.yAxis;
            this.option.xAxis.data = this.myData.xAxis.data;
            this.option.xAxis.show = this.myData.xAxis.show;
            this.option.xAxis.name = this.myData.xAxis.name;
            this.option.yAxis.show = this.myData.yAxis.show;
            this.option.yAxis.name = this.myData.yAxis.name;
            this.option.series = this.myData.series;
        },
        //***发送请求****
        getData(method, url, params) {
            try {
                if (params != null && params != '') {
                    let date = new Date();
                    if (params.day) {
                        date.setDate(date.getDate() - params.day)
                        params['form'] = {'createTime': date}
                        delete params.day;
                    }
                    if (params.seconds) {
                        date.setSeconds(date.getSeconds() - params.seconds)
                        params['form'] = {'createTime': date}
                        delete params.seconds;
                    }
                    if (params.minutes) {
                        date.setMinutes(date.getMinutes() - params.minutes)
                        params['form'] = {'createTime': date}
                        delete params.minutes;
                    }
                }
                // 判断是否包换动态参数'
                // if (this.echartsValue !== null && this.echartsValue !== '') {
                //     params['form'] = {'key': this.key}
                // }
                return this.$myAxios.request(method, url, params).then((res) => {
                    return res;
                });
            } catch (e) {
                return 0;
            }
        },

        //接口数据
        async init(method, url, requstForm) {
            if (url && url != "" && method && method != "") {
                let res = await this.getData(method, url, requstForm);
                if (res == 0) {
                    return;
                }
                if (res.data.code == 200) {
                    //判断X轴是否有formartter配置
                    if (this.requstParams.xFormatter) {
                        let xData = eval(this.requstParams.xFormatter)(res);
                        // let seconds = [];
                        // let resData = xData.data.data
                        // for (let i = 0; i < resData.length; i++) {
                        //   var seconds1 = new Date(resData[i].createTime).getSeconds();
                        //   seconds.push(seconds1);
                        // }
                        // new Date(resData[i].createTime).toLocaleTimeString()
                        this.$set(this.option.xAxis, "data", xData);
                    }
                    // this.initDataMapping(res);
                    if (this.requstParams.yFormatter) {
                        let series = []
                        let yData = eval(this.requstParams.yFormatter)(res, this.myData);
                        for (let i in yData) {
                            let serieCopy = {}
                            serieCopy.name = this.option.series[i].name;
                            serieCopy.type = 'line';
                            serieCopy.data = yData[i];
                            serieCopy.lineStyle = {
                                'color': this.option.series[i].lineStyle.color,
                                'width': this.option.series[i].lineStyle.width
                            },
                                series.push(serieCopy);
                        }
                        this.$set(this.option, "series", series);
                    }
                    // this.initChart();
                    this.chartView.setOption(this.option);
                }
            }
        },

//
//     (val, option)=>{
//     let series = option.series
//     if (series) {
//         let resSeriesData = []
//         for (let i = 0; i < series.length; i++) {
//             //当前字典的data
//             let dicValue = series[i].dictionary
//
//             let data = [];
//             for (let j = 0; j < val.data.data.records.length; j++) {
//                 if ('CPU%' in val.data.data.records[j].form) {
//                     let resDic = val.data.data.records[j].form['CPU%']
//                     var pattern =/[\d\.]+/g;
//                     var result = resDic.match(pattern);
//                     data.push(result)
//                 }
//             }
//             resSeriesData.push(data)
//         }
//         return resSeriesData
//     }
// }

        //   (val, option)=>{
        //   let series = option.series
        //   if (series) {
        //     let resSeriesData = []
        //     for (let i = 0; i < series.length; i++) {
        //         //当前字典的data
        //       let dicValue = series[i].dictionary
        //
        //       let data = [];
        //       for (let j = 0; j < val.data.data.length; j++) {
        //         if (dicValue in val.data.data[j].form) {
        //           data.push(val.data.data[j].form[dicValue])
        //         }
        //       }
        //       resSeriesData.push(data)
        //     }
        //     return resSeriesData
        //   }
        // }

        //数据映射
        // initDataMapping(res) {
        //   let series = this.option.series
        //   if (res) {
        //     let resSeriesData = []
        //     for (let i = 0; i < series.length; i++) {
        //       let dicValue = series[i].dictionary
        //       //当前字典的data
        //       let data = [];
        //       for (let j = 0; j < res.data.data.length; j++) {
        //         if (dicValue in res.data.data[j].form) {
        //           data.push(res.data.data[j].form[dicValue])
        //         }
        //       }
        //       // this.option.series[i].data = data;
        //       resSeriesData.push(data)
        //     }
        //     return resSeriesData
        //   }
        // },
        //   (val) => {
        //   let seconds = [];
        //   let resData = val.data.data
        //   for (let i = 0; i < resData.length; i++) {
        //     var seconds1 = new Date(resData[i].createTime).getSeconds();
        //     seconds.push(seconds1);
        //   }
        //   return seconds
        // }

        //X轴formartter
        // xAxisFormatter(requstForm){
        //   let xFormatter;
        //   if (typeof requstForm.xFormatter != "function") {
        //     xFormatter = eval(requstForm.xFormatter);
        //   } else {
        //     xFormatter = requstForm.xFormatter;
        //   }
        //   return xFormatter;
        // }
        // ,
        //y轴formartter
        // yAxisFormatter(requstForm){
        //   let yFormatter;
        //   if (typeof requstForm.yFormatter != "function") {
        //     yFormatter = eval(requstForm.yFormatter);
        //   } else {
        //     yFormatter = requstForm.yFormatter;
        //   }
        //   return yFormatter;
        // },
        /**
         * 刷新图列大小，刷新图片大小
         */
        resizeContainer() {
            this.$nextTick(() => {
                let container = this.$refs.line;
                container.style.width = this.requstParams.newWidth + 'px';
                container.style.height = this.requstParams.newHeight + 'px';
                this.chartView.resize();
            })
        },
        /**
         * 销毁图表实例
         */
        destroyCharts() {
            if (
                this.chartView != null &&
                this.chartView != "" &&
                this.chartView != undefined
            ) {
                this.chartView.dispose();
            }
        },
        //add**
        // addSeries(){
        //   let result = [
        //     {name: "A", data: [0, 3, 6]},
        //     {name: "B", data: [101, 2, 5]},
        //     {name: "C", data: [0, 5, 8]},
        //     {name: "D", data: [45, 3, 6]},
        //   ];
        //   let newResult = [];
        //   if (result.length) {
        //     result.forEach((item) => {
        //       newResult.push({
        //         showSymbol: false,
        //         type: "line",
        //         smooth: false,
        //         lineStyle: {
        //           color: '',
        //           width: 2,
        //         },
        //         ...item,
        //       });
        //     });
        //   }
        //   this.option.series = newResult;
        //   this.$nextTick(() => {
        //     this.chartView.dispose();
        //     this.initChart();
        //   });
        // },

        //update**
        // updateApi(){
        //   this.destroyCharts();
        //   this.initData();
        //   this.initChart();
        // },

        /**
         * 获取远程数据
         */
        getRemoteData(val) {
            let url = this.requstParams.initUrl;
            let method = this.requstParams.initMethod;
            if (url && method) {
                let form = this.getRequestParam()
                if (val) {
                    form['form'] = {'key': val}
                }
                this.init(method, url, form);
            }
        },

        /**
         * 定时轮询刷新数据
         * @param intervalTime
         */
        initTimer(intervalTime) {
            this.timer = setInterval(() => {
                this.getRemoteData();
            }, intervalTime);
        },
        /**
         * 重置定时器
         * @param intervalTime
         */
        resetTimer(intervalTime) {
            this.closeTimer();
            this.initTimer(intervalTime)
        },
        //连接websocket
        // wsSubscribe(par)
        // {
        //   let header = {};
        //   if (par && Object.keys(par).length > 0) {
        //     Object.assign(header, par);
        //   }
        //   let that = this;
        //   let model = {};
        //   this.$set(model, this.modelName, (res) => {
        //     this.$set(this.option.series[0], "data", res.data["val"]);
        //     this.$set(this.option.xAxis, "data", res.data["time"]);
        //     console.log("【chart】数据来了");
        //     this.initChart();
        //   });
        //   let subscriber = {
        //     topic: that,
        //     model: model,
        //   };
        //   //发起topic主题订阅
        //   let ws = this.$ws.getWs(this.linkName);
        //   if (!ws) {
        //     console.log("ws未连接");
        //   } else {
        //     ws.subscribeToModel(subscriber.topic, subscriber.model, header);
        //   }
        // }
        // ,
        //取消订阅
        // cancelSubscribe()
        // {
        //   let ws = this.$ws.getWs(this.linkName);
        //   if (ws) {
        //     ws.unSubscribe(this.requstParams.chartTopic);
        //   }
        // }
        // ,
    },
}
</script>
<style lang="less" scoped>
.container {
    height: 260px;
    width: 50vw;
    margin: 0px 33px 0 33px;
}
</style>
